<?php
namespace app\services;


use app\models\Activities;
use app\models\ActivityEnlists;

class ActivityService extends ServiceBase
{
    /**
     * @param array $params
     * @param int $page
     * @param int $pagesize
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getLists($params=[], $page=1, $pagesize=10)
    {
        return Activities::lists($params, $page, $pagesize);
    }

    /**
     * @param $id
     * @return Activities|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetail($id)
    {
        $activities = Activities::find($id);

        if ($activities instanceof Activities) {
            return $activities;
        }

        throw new \Exception('活动不存在');
    }

    /**
     * 添加组织
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public function add($params)
    {
        try {
            $activity = new Activities();

            foreach ($params as $key => $val) {
                $activity->$key = $val;
            }
            $activity->save();

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * 更新组织
     * @param Activities $activity
     * @param $params
     */
    public function update(Activities $activity, $params)
    {
        foreach ($params as $key => $val) {
            $activity->$key = $val;
        }
        $activity->save();
    }

    /**
     * 上架组织
     * @param Activities $organization
     */
    public function enable(Activities $organization)
    {
        $organization->status = 1;
        $organization->save();
    }

    /**
     * 下架组织
     * @param Activities $organization
     */
    public function disable(Activities $organization)
    {
        $organization->status = 0;
        $organization->save();
    }

    public function checkSignup($activityId, $userId)
    {
        $enroll = ActivityEnlists::where(['activityId' => $activityId, 'userId' => $userId])->find();

        return $enroll?1:0;
    }
}